package bt.basics.common.utils;

import bt.basics.common.exception.CustomizeException;
import bt.basics.common.exception.ErrorCode;
import cn.hutool.http.HtmlUtil;

import java.util.Map;

public class ResponseUtils {

    /**
     * 朗通获取头部信息
     *
     * @param xml
     * @param type 1:获取头部实体类 2获取分页查询的body对应的实体类 3：获取不是分页查询的body对应的实体类 6.档案归档返回信息
     * @param cl
     * @return
     */
    public static Object getLZResponseEtity(String xml, Integer type, Class<?> cl) {
        Object object = null;
        boolean decodeType = true;
        try {
            if (!xml.contains("head")) {
                throw new CustomizeException(ErrorCode.OTHER_SYSTEM_ERROR);
            }
            if (type == 1) {
                xml = HtmlUtil.removeHtmlTag(xml, "body");
                xml = HtmlUtil.unwrapHtmlTag(xml, "head");
                Map<String, Object> map = XmlUtils.xml2Map(xml);
                object = MapUtils.parsePoje(map, cl);
            }

            if (type == 2 || type == 3) {
                xml = HtmlUtil.removeHtmlTag(xml, "head");
                object = XmlUtils.unMarshal(cl, xml);
            }
            if (type == 3) {
                xml = HtmlUtil.unwrapHtmlTag(xml, "body");
                Map<String, Object> map = XmlUtils.xml2Map(xml);
                object = MapUtils.parsePoje(map, cl);
            }
            if (type == 4) {
                xml = HtmlUtil.unwrapHtmlTag(xml, "body");
                xml = HtmlUtil.unwrapHtmlTag(xml, "ROWSET");
                xml = HtmlUtil.unwrapHtmlTag(xml, "xml");
                xml = HtmlUtil.removeHtmlTag(xml, "head");
                object = XmlUtils.unMarshal(cl, xml);
            }
            if(type==5){
                xml = HtmlUtil.removeHtmlTag(xml, "head");
                xml = HtmlUtil.unwrapHtmlTag(xml, "body");
                object = XmlUtils.unMarshal(cl, xml);
            }
            if(type==6){
                xml = HtmlUtil.removeHtmlTag(xml, "body");
                xml = HtmlUtil.unwrapHtmlTag(xml, "head");
                xml = HtmlUtil.unwrapHtmlTag(xml, "response");
                Map<String, Object> map = XmlUtils.xml2Map(xml);
                object = MapUtils.parsePoje(map, cl);
            }
            if(type==7){
                xml = HtmlUtil.removeHtmlTag(xml, "body");
                xml = HtmlUtil.unwrapHtmlTag(xml, "response");
                object = XmlUtils.unMarshal(cl, xml);
            }

        } catch (Exception e) {
            decodeType = false;
        }
        if (!decodeType) {
            throw new CustomizeException(ErrorCode.OTHER_SYSTEM_ERROR);
        }
        return object;
    }

}
